package com.cuckoo.mall.thus.menufoucs;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bgn.baseframe.base.BaseFragment;
import com.cuckoo.mall.R;
import com.cuckoo.mall.network.Constants;
import com.orhanobut.logger.Logger;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class FoucsFragment extends BaseFragment {

    @BindView(R.id.default_page_view)
    LinearLayout linearLayoutDefault;
    @BindView(R.id.swipe_view)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.webview)
    WebView myWebview;
    private String url = "https://www.facebook.com/ThusMall-200566957267690/?modal=admin_todo_tour";

    public boolean hasError = false;

    @Override
    protected View initView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_menu_foucs, null);
        ButterKnife.bind(this, rootView);
        initWebView();
        initSwipe();
        intDefualtView();
        return rootView;
    }

    private void intDefualtView() {
        linearLayoutDefault.setVisibility(View.GONE);
        TextView textView = linearLayoutDefault.findViewById(R.id.tv_load);
        ImageView imageView = linearLayoutDefault.findViewById(R.id.iv_default_lcon);
        imageView.setImageResource(R.mipmap.default_web_miss);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingView();
                hasError = false;
                myWebview.loadUrl(url);
            }
        });
    }

    private void initSwipe() {
        swipeRefreshLayout.setEnabled(true);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                hasError = false;
                swipeRefreshLayout.setRefreshing(false);
                myWebview.loadUrl(url);
            }
        });
    }


    private void initWebView() {

        myWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        myWebview.getSettings().setJavaScriptEnabled(true);
        // 开启DOM缓存，开启LocalStorage存储（html5的本地存储方式）
        myWebview.getSettings().setDomStorageEnabled(true);

        myWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains(Constants.APP_HOST)) {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                } else {
                    view.loadUrl(url);

                }
                return true;
            }


            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                showDefaultView();
                hideLoadingView();
                hasError = true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                hideLoadingView();
                hideDefaultView();
                if (hasError) {
                    linearLayoutDefault.setVisibility(View.VISIBLE);
                } else {
                    linearLayoutDefault.setVisibility(View.GONE);
                }
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (isNetworkerConnectHint()) {
                    super.onPageStarted(view, url, favicon);
                } else {
                    showDefaultView();
                }

            }

//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                if (error.getCertificate() != null) {
//                    handler.proceed(); // 接受证书
//                } else {
//                    handler.cancel(); // 接受证书
//                }
//            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                Logger.d("TTT:" + "onReceivedHttpError");
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                //Logger.d("错误：" + error.getDescription().toString() + "地址：" + view.getUrl());
                super.onReceivedError(view, request, error);
                hideLoadingView();
                Logger.d("TTT:" + "onReceivedError");
            }
        });

    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(url) || !isNetworkerConnectHint()) {
            showDefaultView();
        } else {
            // showLoadingView();
            myWebview.loadUrl(url);
        }

    }

    @Override
    public void onDefaultViewClick(int tag) {
        super.onDefaultViewClick(tag);
        if (isNetworkerConnectHint()) {
            myWebview.loadUrl(url);
            showLoadingView();
        }
    }


}
